var orders = createOrders();
var url = require('url');

require('http').createServer(function (req, res) {
    var matchStrings = req.url.match("^/orders");
    if (matchStrings != null && req.method == "GET") {

        var url_parts = url.parse(req.url, true);
        var query = url_parts.query;
        var page = query.page != null ? query.page : 1;
        var size = query.size != null ? query.size : 10;

        var orders = findOrders(page, size);

        res.setHeader('Link', generateLinks(page, size));
        res.writeHead(200);
        res.write(JSON.stringify(orders));
        res.end();
    }
    else {
        res.writeHead(400);
        res.end()
    }
}).listen(8888);

function generateLinks(page, size) {
    var links = new Array();
    if (page != 1) {
        links.push("/orders?page=1&size=" + size + ">; rel='first'");
        links.push("/orders?page=" + (parseInt(page) - 1) + "&size=" + size + ">; rel='prev'");
    }
    var ordersLength = orders.length;
    var lastPage = Math.ceil(ordersLength / size);

    if (page != lastPage) {
        links.push("/orders?page=" + (parseInt(page) + 1) + "&size=" + size + ">; rel='next'");
        links.push("/orders?page=" + lastPage + "&size=" + size + ">; rel='last'");
    }
    return links;
}

function findOrders(page, size) {
    var ordersTmp = new Array();
    var offset = (page - 1) * size;
    for (var i = 1; i < (parseInt(size) + 1); i++) {
        if (offset + i >= orders.length) {
            break;
        }
        ordersTmp[i - 1] = orders[offset + i];
    }
    return ordersTmp;
}

function createOrders() {
    var orders = new Array();
    for (var i = 0; i < 28; i++) {
        orders.push({"orderId": i, "orderName": i + "orderName" + i});
    }
    return orders;
}